package com.xinghai.system.service.impl;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xinghai.common.constant.CacheConstants;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.exception.ServiceException;

import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.DataUpdateDTO;
import com.xinghai.system.domain.entity.RechargePointsDTO;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.*;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdOrderMapper;

/**
 * 订单模块Service业务层处理
 *
 * @author xinghai
 * @date 2024-12-04
 */
@Service
public class QdOrderServiceImpl extends ServiceImpl<QdOrderMapper, QdOrder>
        implements IQdOrderService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private IQdUserService qdUserService;
    @Autowired
    private IQdPayService qdPayService;
    @Autowired
    private IQdPayOrderService qdPayOrderService;
    @Autowired
    private IQdPayOrderInfoService qdPayOrderInfoService;
    @Autowired
    private IQdStoreService storeService;
    @Autowired
    private IQdChangeOrderService changeOrderService;
    @Autowired
    private IQdDealInfoService dealInfoService;
    @Autowired
    private IQdUserWalletService userWalletService;
    @Autowired
    private IQdUserWalletLogService walletLogService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询订单模块列表
     *
     * @param qdOrder 订单模块
     * @return 订单模块集合
     */
    @Override
    public List<QdOrder> list(QdOrder qdOrder) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        if (qdOrder.getStatus()!= null  && !qdOrder.getStatus().isEmpty()){
            queryWrapper.apply("FIND_IN_SET(status,'"+qdOrder.getStatus()+"')");
        }
        if (qdOrder.getParams().get("beginCreateTime")!= null && !"".equals(qdOrder.getParams().get("beginCreateTime"))
        &&qdOrder.getParams().get("endCreateTime")!= null && !"".equals(qdOrder.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdOrder.getParams().get("beginCreateTime"),qdOrder.getParams().get("endCreateTime"));
        }
        if (qdOrder.getOrderNo()!= null  && !qdOrder.getOrderNo().isEmpty()){
            queryWrapper.eq("order_no", qdOrder.getOrderNo());
        }
        if (qdOrder.getSellerUserName()!= null  && !qdOrder.getSellerUserName().isEmpty()){
            queryWrapper.like("seller_user_name", qdOrder.getSellerUserName());
        }
        if (qdOrder.getSellerUserPhone()!= null  && !qdOrder.getSellerUserPhone().isEmpty()){
            queryWrapper.eq("seller_user_phone", qdOrder.getSellerUserPhone());
        }
        if (qdOrder.getSellerBalance()!= null  && !qdOrder.getSellerBalance().isEmpty()){
            queryWrapper.eq("seller_balance", qdOrder.getSellerBalance());
        }
        if (qdOrder.getBuyerUserName()!= null  && !qdOrder.getBuyerUserName().isEmpty()){
            queryWrapper.like("buyer_user_name", qdOrder.getBuyerUserName());
        }
        if (qdOrder.getBuyerUserPhone()!= null  && !qdOrder.getBuyerUserPhone().isEmpty()){
            queryWrapper.eq("buyer_user_phone", qdOrder.getBuyerUserPhone());
        }
        if (qdOrder.getBuyerBalance()!= null  && !qdOrder.getBuyerBalance().isEmpty()){
            queryWrapper.eq("buyer_balance", qdOrder.getBuyerBalance());
        }
        if (qdOrder.getBuyerUserId()!= null){
            queryWrapper.eq("buyer_user_id", qdOrder.getBuyerUserId());
        }
        if (qdOrder.getSellerUserId()!= null){
            queryWrapper.eq("seller_user_id", qdOrder.getSellerUserId());
        }
        if (qdOrder.getStoreId()!= null){
            queryWrapper.eq("store_id", qdOrder.getStoreId());
        }
        if (qdOrder.getSellerStatus()!= null  && !qdOrder.getSellerStatus().isEmpty()){
            queryWrapper.eq("seller_status", qdOrder.getSellerStatus());
        }
        if (qdOrder.getBuyerStatus()!= null  && !qdOrder.getBuyerStatus().isEmpty()){
            queryWrapper.eq("buyer_status", qdOrder.getBuyerStatus());
        }
        if (qdOrder.getBuyerStatusStr()!= null  && !qdOrder.getBuyerStatusStr().isEmpty()){
            queryWrapper.apply("FIND_IN_SET(buyer_status,'"+qdOrder.getBuyerStatusStr()+"')");
            queryWrapper.ne("seller_status", "0");
        }
        if (qdOrder.getBuyerType()!= null  && !qdOrder.getBuyerType().isEmpty()){
            queryWrapper.apply("FIND_IN_SET(buyer_type,'"+qdOrder.getBuyerType()+"')");
        }
        if (qdOrder.getGoodName()!= null  && !qdOrder.getGoodName().isEmpty()){
            queryWrapper.like("good_name", qdOrder.getGoodName());
        }
        if (qdOrder.getDealTime()!= null){
            queryWrapper.apply("date_format(deal_time,'%Y-%m-%d') = '"+ DateUtils.dateTime(qdOrder.getDealTime()) +"'");
        }
        if(qdOrder.isBuyerFlag() && qdOrder.getSearchValue()!=null && !qdOrder.getSearchValue().isEmpty()){
            queryWrapper.and(m->m.like("buyer_user_name", qdOrder.getSearchValue())
                    .or().like("buyer_user_phone", qdOrder.getSearchValue())
            );
        }
        if(qdOrder.getSearchValue()!=null && !qdOrder.getSearchValue().isEmpty()){
            queryWrapper.and(m->m.like("seller_user_name", qdOrder.getSearchValue())
                    .or().like("seller_user_phone", qdOrder.getSearchValue())
                    .or().like("buyer_user_name", qdOrder.getSearchValue())
                    .or().like("buyer_user_phone", qdOrder.getSearchValue())
                    );
        }
        if (qdOrder.getUserId()!= null){
            queryWrapper.and(m->m.eq("buyer_user_id", qdOrder.getUserId()).or().eq("seller_user_id", qdOrder.getUserId()));
        }
        if (qdOrder.getMinPrice()!= null&&qdOrder.getMaxPrice()!= null){
            queryWrapper.ge("price", qdOrder.getMinPrice()).le("price", qdOrder.getMaxPrice()).orderByDesc("price").last("limit 1");
        }
        return this.list(queryWrapper);
    }

    /**
     * 删除订单模块信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdOrder qdOrder = new QdOrder();
            qdOrder.setId(id);
            qdOrder.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdOrder);
        }
        return this.removeById(id);
    }

    /**
     * 批量删除订单模块信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdOrder> collect = Arrays.stream(ids).map(m -> {
                QdOrder qdOrder = new QdOrder();
                qdOrder.setId(m);
                qdOrder.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdOrder;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入订单模块信息
     *
     * @param list 订单模块信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdOrder> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdOrderMapper qdOrderMapper = sqlSession.getMapper(QdOrderMapper.class);
            list.forEach(qdOrderMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    @Transactional
    public synchronized boolean addOrder(QdUser user, QdOrder qdOrder) {
        QdOrder order = getById(qdOrder.getId());
        if (!"0".equals(order.getSellerStatus())){
            throw new ServiceException("下单失败，请刷新重试");
        }
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        qdOrder.setGoodImg(cacheMap.getGroupOneImage());
        qdOrder.setGoodId(cacheMap.getGroupOneGoodId());
        qdOrder.setGoodName(cacheMap.getGroupOneName());
        qdOrder.setSellerStatus("1");
        qdOrder.setBuyerStatus("0");
        qdOrder.setBuyerBalance("0");
        qdOrder.setBuyerUserId(user.getId());
        qdOrder.setBuyerUserName(user.getNickName());
        qdOrder.setBuyerUserPhone(user.getUserPhone());
        qdOrder.setDealTime(new Date());
        //更新订单
        UpdateWrapper<QdOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", qdOrder.getId());
        updateWrapper.eq("seller_status", "0");
        boolean update = this.update(qdOrder, updateWrapper);
        if (!update){
            throw new ServiceException("下单失败，请刷新重试");
        }
        //20241213 购买后计算业绩
        //累计购买上架费
        QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(user.getId()));
        wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(qdOrder.getPrice()));
        wallet.setNowMoney(wallet.getNowMoney().add(qdOrder.getPrice()));
        wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
        wallet.setListingFee(wallet.getListingFee().add(qdOrder.getListingFee()));
        userWalletService.updateById(wallet);
        //更新业绩
        QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(qdOrder.getSellerUserId()));
        wallet1.setAchievement(wallet1.getAchievement().add(qdOrder.getPrice()));
        userWalletService.updateById(wallet1);

        QdUser sellerUser = qdUserService.getById(qdOrder.getSellerUserId());
        //插入对账信息
        QdPay qdPay = new QdPay();
        qdPay.setBuyerBankInfo(user.getBankInfo());
        qdPay.setBuyerBankNo(user.getBankNo());
        qdPay.setBuyerBankName(user.getBankName());
        qdPay.setBuyerUserId(user.getId());
        qdPay.setBuyerUserName(user.getNickName());
        qdPay.setBuyerUserPhone(user.getUserPhone());
        qdPay.setBuyerBalance("0");
        qdPay.setAmount(qdOrder.getPrice().subtract(qdOrder.getListingFee()).subtract(qdOrder.getPushAmount()));
        qdPay.setSellerUserId(qdOrder.getSellerUserId());
        qdPay.setSellerUserName(qdOrder.getSellerUserName());
        qdPay.setSellerUserPhone(qdOrder.getSellerUserPhone());
        qdPay.setSellerBalance("0");
        qdPay.setStatus("0");
        qdPay.setOrderNo(qdOrder.getOrderNo());
        qdPay.setSellerBankInfo(sellerUser.getBankInfo());
        qdPay.setSellerBankNo(sellerUser.getBankNo());
        qdPay.setSellerBankName(sellerUser.getBankName());
        return qdPayService.save(qdPay);
    }

    @Override
    @Transactional
    public boolean assignBuyer(String ids, Long id) {
        QdUser qdUser = qdUserService.getById(id);
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        List<QdOrder> list = this.list(queryWrapper);

        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + qdUser.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(qdUser.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + qdUser.getAscriptionStore(), cacheMap);
        }
        String buyType = "4";
        if ((DateUtils.parseDate(cacheMap.getReservationStartDateDay()).compareTo(DateUtils.getNowDate()) < 1
                ||DateUtils.parseDate(cacheMap.getReservationEndDateDay()).compareTo(DateUtils.getNowDate())>-1)){
            buyType = "3";
        }
        BigDecimal bili = qdUser.getGiftValue();
        if (bili==null){
            bili = cacheMap.getAppreciation();
        }
        QdStoreVo finalCacheMap = cacheMap;
        BigDecimal finalBili = bili;
        String finalBuyType = buyType;
        List<QdOrder> orderList = list.stream().peek(m -> {
            if (!"0".equals(m.getSellerStatus())) {
                throw new ServiceException("订单状态已经更新,请刷新重试");
            }
            m.setSellerStatus("1");
            m.setBuyerStatus("0");
            m.setBuyerUserId(qdUser.getId());
            m.setBuyerUserName(qdUser.getNickName());
            m.setBuyerBalance("0");
            m.setBuyerUserPhone(qdUser.getUserPhone());
            m.setBuyerType(finalBuyType);
            m.setListingFee(m.getPrice().multiply(finalCacheMap.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
            m.setNewPrice(m.getPrice().multiply(finalBili.add(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
            m.setPushAmount(m.getPrice().multiply(finalCacheMap.getPushFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
            m.setDealTime(new Date());
            //20241213 购买后计算业绩
            //累计购买上架费
            QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(m.getBuyerUserId()));
            wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(m.getPrice()));
            wallet.setNowMoney(wallet.getNowMoney().add(m.getPrice()));
            wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
            wallet.setListingFee(wallet.getListingFee().add(m.getListingFee()));
            userWalletService.updateById(wallet);
            //更新业绩
            QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(m.getSellerUserId()));
            wallet1.setAchievement(wallet1.getAchievement().add(m.getPrice()));
            userWalletService.updateById(wallet1);

            QdUser sellerUser = qdUserService.getById(m.getSellerUserId());
            //插入对账信息
            QdPay qdPay = new QdPay();
            qdPay.setBuyerBankInfo(qdUser.getBankInfo());
            qdPay.setBuyerBankNo(qdUser.getBankNo());
            qdPay.setBuyerBankName(qdUser.getBankName());
            qdPay.setBuyerUserId(qdUser.getId());
            qdPay.setBuyerUserName(qdUser.getNickName());
            qdPay.setBuyerUserPhone(qdUser.getUserPhone());
            qdPay.setBuyerBalance("0");
            qdPay.setAmount(m.getPrice().subtract(m.getListingFee()).subtract(m.getPushAmount()));
            qdPay.setSellerUserId(m.getSellerUserId());
            qdPay.setSellerUserName(m.getSellerUserName());
            qdPay.setSellerUserPhone(m.getSellerUserPhone());
            qdPay.setSellerBalance("0");
            qdPay.setStatus("0");
            qdPay.setOrderNo(m.getOrderNo());
            qdPay.setSellerBankInfo(sellerUser.getBankInfo());
            qdPay.setSellerBankNo(sellerUser.getBankNo());
            qdPay.setSellerBankName(sellerUser.getBankName());
            qdPayService.save(qdPay);
        }).collect(Collectors.toList());
        return updateBatchById(orderList);
    }

    @Override
    public boolean closeOrder(String ids) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        List<QdOrder> list = this.list(queryWrapper);
        list.forEach(m -> {
            if (!"0".equals(m.getSellerStatus())) {
                throw new ServiceException("订单状态已经更新,请刷新重试");
            }
        });
        UpdateWrapper<QdOrder> qdOrderUpdateWrapper = new UpdateWrapper<>();
        qdOrderUpdateWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        QdOrder qdOrder = new QdOrder();
        qdOrder.setStatus("1");
        return this.update(qdOrder, qdOrderUpdateWrapper);
    }

    @Override
    public boolean openOrder(String ids) {
        UpdateWrapper<QdOrder> qdOrderUpdateWrapper = new UpdateWrapper<>();
        qdOrderUpdateWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        QdOrder qdOrder = new QdOrder();
        qdOrder.setStatus("0");
        return this.update(qdOrder, qdOrderUpdateWrapper);
    }

    @Override
    @Transactional
    public boolean changeSeller(String ids, Long id) {
        QdUser qdUser = qdUserService.getById(id);
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        List<QdOrder> list = this.list(queryWrapper);
        List<QdOrder> orderList = list.stream().peek(m -> {
            if (!"0".equals(m.getSellerStatus())) {
                throw new ServiceException("订单状态已经更新,请刷新重试");
            }
            m.setSellerStatus("0");
            m.setSellerUserId(qdUser.getId());
            m.setSellerUserName(qdUser.getNickName());
            m.setSellerBalance("0");
            m.setSellerUserPhone(qdUser.getUserPhone());
        }).collect(Collectors.toList());
        return updateBatchById(orderList);
    }

    @Override
    @Transactional
    public boolean genPayOrder(Long storeId) {
        QdPayOrder payOrder = new QdPayOrder();
        payOrder.setStoreId(storeId);
        payOrder.setGenDate(new Date());
        List<QdPayOrder> list = qdPayOrderService.list(payOrder);
        if (!list.isEmpty()){
            throw new ServiceException("今日对账单已经生成！");
        }
        QdOrder order = new QdOrder();
        order.setStoreId(storeId);
        order.setStatus("0");
        order.setSellerStatus("0");
        List<QdOrder> list1 = list(order);
        if (!list1.isEmpty()){
            throw new ServiceException("还有待出售的订单，无法生成对账单！");
        }
        QdOrder order1 = new QdOrder();
        order1.setStoreId(storeId);
        order1.setBuyerStatus("0");
        order1.setSellerStatus("1");
        order1.setStatus("0");
        List<QdOrder> list2 = list(order1);
        list2.forEach(m->{
            m.setBuyerStatus("1");
        });
        updateBatchById(list2);//修改订单状态为待平账

        List<QdPayOrderInfo> memberDealData = baseMapper.getMemberDealData(storeId);
        QdStore store = storeService.getById(storeId);
        List<QdPayOrderInfo> orderList = memberDealData.stream().filter(m -> m.getBuyNum() > 0 || m.getSellNum() > 0).collect(Collectors.toList());
        QdPayOrder qdPayOrder = new QdPayOrder();
        qdPayOrder.setGenDate(new Date());
        qdPayOrder.setOrderNum(orderList.stream().mapToInt(QdPayOrderInfo::getBuyNum).sum());
        qdPayOrder.setStoreId(storeId);
        qdPayOrder.setMemberNum(orderList.size());
        qdPayOrder.setBuyAmount(orderList.stream().map(QdPayOrderInfo::getBuyAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        qdPayOrder.setSellAmount(orderList.stream().map(QdPayOrderInfo::getSellAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        qdPayOrder.setStoreName(store.getStoreName());
        qdPayOrder.setStatus("0");
        qdPayOrderService.save(qdPayOrder);
        if (memberDealData.isEmpty()){
            return true;
        }
        orderList = orderList.stream().peek(m->{
            m.setDiff(m.getSellAmount().subtract(m.getBuyAmount()));
            m.setLinkPayOrder(qdPayOrder.getId());
        }).collect(Collectors.toList());
        qdPayOrderInfoService.saveBatch(orderList);
        //买家列表按金额大小倒序
        List<QdPayOrderInfo> aList = orderList.stream().filter(m -> m.getDiff().compareTo(BigDecimal.ZERO) > 0).sorted(Comparator.comparing(QdPayOrderInfo::getDiff).reversed()).collect(Collectors.toList());
        //卖家列表
        List<QdPayOrderInfo> bList = orderList.stream().filter(m -> m.getDiff().compareTo(BigDecimal.ZERO) < 0).sorted(Comparator.comparing(QdPayOrderInfo::getDiff)).collect(Collectors.toList());
        //卖家列表按卖出金额大小倒序
        //买家和卖家进行差额平账
        boolean flag = true;
        BigDecimal diff = BigDecimal.ZERO;
        BigDecimal add = BigDecimal.ZERO;
        int j = 0;
        List<QdDealInfo> dealInfoList = new ArrayList<>();
        for (int i = 0; i < aList.size(); i++) {
            QdPayOrderInfo a = aList.get(i);
            diff = diff.add(a.getDiff());
            QdDealInfo dealInfo = new QdDealInfo();
            dealInfo.setUserId(a.getUserId());
            dealInfo.setUserName(a.getUserName());
            dealInfo.setUserPhone(a.getUserPhone());
            dealInfo.setOrderInfoId(a.getId());
            dealInfo.setStoreId(a.getStoreId());
            for (; j < bList.size(); j++){
                QdPayOrderInfo b = bList.get(j);
                QdDealInfo dealInfo1 = new QdDealInfo();
                dealInfo1.setUserId(b.getUserId());
                dealInfo1.setUserName(b.getUserName());
                dealInfo1.setUserPhone(b.getUserPhone());
                dealInfo1.setOrderInfoId(b.getId());
                dealInfo1.setStoreId(b.getStoreId());

                dealInfo1.setPayBankInfo(a.getBankInfo());
                dealInfo1.setPayBankName(a.getBankName());
                dealInfo1.setPayBankNo(a.getBankNo());
                dealInfo1.setPayUserId(a.getUserId());
                dealInfo1.setPayUserName(a.getUserName());
                dealInfo1.setPayUserPhone(a.getUserPhone());


                dealInfo.setPayBankInfo(b.getBankInfo());
                dealInfo.setPayBankName(b.getBankName());
                dealInfo.setPayBankNo(b.getBankNo());
                dealInfo.setPayUserId(b.getUserId());
                dealInfo.setPayUserName(b.getUserName());
                dealInfo.setPayUserPhone(b.getUserPhone());

                if (flag){
                    add = diff.add(b.getDiff());
                }else {
                    if (diff.compareTo(BigDecimal.ZERO)>=0){
                        BigDecimal bigDecimal = add;
                        add = diff;
                        flag = true;
                        //金额去相反数

                        dealInfo1.setAmount(bigDecimal);
                        dealInfo.setAmount(bigDecimal.negate());
                        QdDealInfo d1 = new QdDealInfo();
                        QdDealInfo d2 = new QdDealInfo();
                        BeanUtils.copyProperties(dealInfo1,d1);
                        BeanUtils.copyProperties(dealInfo,d2);
                        dealInfoList.add(d2);
                        dealInfoList.add(d1);
                        continue;
                    }
                }
                if (add.compareTo(BigDecimal.ZERO)>=0 && diff.compareTo(BigDecimal.ZERO)>=0){
                    diff = add;
                    dealInfo1.setAmount(b.getDiff());
                    dealInfo.setAmount(b.getDiff().negate());
                    flag = true;
                    //bList = bList.subList(j+1,bList.size());
                    //j--;
                }else if (add.compareTo(BigDecimal.ZERO)>=0 && diff.compareTo(BigDecimal.ZERO)<0){
                    System.out.println("11111111111111111111111");
                }else if (add.compareTo(BigDecimal.ZERO)<0 && diff.compareTo(BigDecimal.ZERO)>=0){
                    BigDecimal bigDecimal = diff;
                    dealInfo1.setAmount(bigDecimal.negate());
                    dealInfo.setAmount(bigDecimal);
                    diff = add;

                    QdDealInfo d1 = new QdDealInfo();
                    QdDealInfo d2 = new QdDealInfo();
                    BeanUtils.copyProperties(dealInfo1,d1);
                    BeanUtils.copyProperties(dealInfo,d2);
                    dealInfoList.add(d2);
                    dealInfoList.add(d1);
//                    dealInfoList.add(dealInfo);
//                    dealInfoList.add(dealInfo1);
                    //j--;
                    flag = false;
                    break;
                }else{
                    dealInfo1.setAmount(a.getDiff().negate());
                    dealInfo.setAmount(a.getDiff());

                    QdDealInfo d1 = new QdDealInfo();
                    QdDealInfo d2 = new QdDealInfo();
                    BeanUtils.copyProperties(dealInfo1,d1);
                    BeanUtils.copyProperties(dealInfo,d2);
                    dealInfoList.add(d2);
                    dealInfoList.add(d1);

                    add = diff;
                    //j--;
                    flag = false;
                    break;
                }

                QdDealInfo d1 = new QdDealInfo();
                QdDealInfo d2 = new QdDealInfo();
                BeanUtils.copyProperties(dealInfo1,d1);
                BeanUtils.copyProperties(dealInfo,d2);
                dealInfoList.add(d2);
                dealInfoList.add(d1);

//                dealInfoList.add(dealInfo);
//                dealInfoList.add(dealInfo1);
            }
        }
        return dealInfoService.saveBatch(dealInfoList);
    }

    @Override
    @Transactional
    public boolean flow(String ids, Long storeId) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        queryWrapper.eq("store_id",storeId);
        List<QdOrder> list = this.list(queryWrapper);
        list.forEach(m->{
            if (!"0".equals(m.getBuyerStatus())){
                throw new ServiceException("已生成对账单，无法流拍");
            }
            m.setSellerStatus("0");
            Long buyUserId = m.getBuyerUserId();
            m.setBuyerUserId(null);
            m.setBuyerUserPhone("");
            m.setBuyerUserName("");
            m.setBuyerStatus("0");
            m.setBuyerType("0");
            //20241213 流拍
            //减少累计购买上架费
            QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(buyUserId));
            wallet.setPurchaseAmount(wallet.getPurchaseAmount().subtract(m.getPrice()));
            wallet.setNowMoney(wallet.getNowMoney().subtract(m.getPrice()));
            wallet.setNowOrderNum(wallet.getNowOrderNum()-1);
            wallet.setListingFee(wallet.getListingFee().subtract(m.getListingFee()));
            userWalletService.updateById(wallet);
            //减少更新业绩
            QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(m.getSellerUserId()));
            wallet1.setAchievement(wallet1.getAchievement().subtract(m.getPrice()));
            userWalletService.updateById(wallet1);
            //删除支付单
            QueryWrapper<QdPay> qdPayQueryWrapper = new QueryWrapper<>();
            qdPayQueryWrapper.eq("order_no",m.getOrderNo());
            qdPayService.remove(qdPayQueryWrapper);
        });
        return updateBatchById(list);
    }

    @Override
    @Transactional
    public boolean toNoPay(String ids, Long storeId) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(ids)){
            queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        }
        queryWrapper.eq("store_id",storeId);
        List<QdOrder> list = this.list(queryWrapper);
        list.forEach(m->{
            m.setBuyerStatus("0");
            m.setBuyerUserId(null);
        });
        return updateBatchById(list);
    }

    @Override
    @Transactional
    public boolean listing(String ids, Long storeId) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(ids)){
            queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        }
        queryWrapper.eq("buyer_status","2");
        queryWrapper.eq("store_id",storeId);
        List<QdOrder> list = this.list(queryWrapper);
        //250126 上架积分所需积分扣除
        QdStore store = storeService.getById(storeId);
        boolean b = store.getGroupingFee().compareTo(BigDecimal.ZERO) > 0;
        List<QdOrder> list1 = new ArrayList<>();
        list.forEach(m->{
            m.setBuyerStatus("3");
            if (b){
                try {
                    listingPoints(store, m);
                } catch (ServiceException e) {
                    //list.remove(m);
                }
            }
            list1.add(m);
        });
        if (list1.isEmpty()){
            throw new ServiceException("没有可上架的订单");
        }
        return updateBatchById(list1);
    }

    private void listingPoints(QdStore store, QdOrder m) {
        BigDecimal fee = m.getPrice().multiply(store.getGroupingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
        if (fee.compareTo(BigDecimal.ZERO)>0){
            QdUserWallet userWallet = userWalletService.getByUserId(String.valueOf(m.getBuyerUserId()));
            if (userWallet.getPoints().compareTo(fee)<0){
                throw new ServiceException("积分不足，无法上架，请去购物专区获取积分！！！");
            }
            RechargePointsDTO dto = new RechargePointsDTO();
            dto.setPoints(fee.multiply(BigDecimal.valueOf(-1)));
            dto.setUserId(String.valueOf(userWallet.getUserId()));
            dto.setDetail("订单上架所需积分");
            dto.setType("1");
            userWalletService.rechargePoints(dto);
        }
    }

    @Override
    @Transactional
    public boolean examine(String ids, Long storeId) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(ids)){
            queryWrapper.apply("FIND_IN_SET(id,'"+ids+"')");
        }
        queryWrapper.eq("store_id",storeId);
        queryWrapper.eq("buyer_status","3");
        List<QdOrder> list = this.list(queryWrapper);
        QdStore store = storeService.getById(storeId);
        List<QdOrder> orderList = new ArrayList<>();
        list.forEach(m->{
            m.setBuyerStatus("4");
            QdOrder order = new QdOrder();
            //order.setId(m.getId());
            order.setOrderNo("OD" + IdUtil.getSnowflakeNextId());
            order.setSellerStatus("0");
            order.setSellerUserId(m.getBuyerUserId());
            order.setSellerUserName(m.getBuyerUserName());
            order.setSellerUserPhone(m.getBuyerUserPhone());
            order.setOldPrice(m.getPrice());
            //order.setStatus("2");
            order.setPrice(m.getNewPrice());
            order.setListingFee(m.getNewPrice().multiply(store.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
            order.setStoreId(m.getStoreId());
            order.setGoodId(m.getGoodId());
            order.setGoodImg(m.getGoodImg());
            order.setGoodName(m.getGoodName());
            orderList.add(order);

            //然后增加佣金
            QdUser user = qdUserService.getById(m.getBuyerUserId());
            if (user.getSuperId()!=null){
                //20241214 添加只有今天购买过的用户才能获得佣金
                QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(user.getSuperId()));
                if(wallet1.getNowMoney().compareTo(BigDecimal.ZERO)>0){
                    wallet1.setAllWallet(wallet1.getAllWallet().add(m.getPushAmount()));
                    wallet1.setWithdrawalWallet(wallet1.getWithdrawalWallet().add(m.getPushAmount()));
                    userWalletService.updateById(wallet1);
                    //插入日志
                    QdUserWalletLog qdUserWalletLog = new QdUserWalletLog();
                    qdUserWalletLog.setUserId(user.getSuperId());
                    qdUserWalletLog.setUserPhone(user.getSuperUserPhone());
                    qdUserWalletLog.setChangeAmount(m.getPushAmount());
                    qdUserWalletLog.setType("1");
                    qdUserWalletLog.setDetail(String.format("来自【%s】的佣金",m.getBuyerUserName()));
                    walletLogService.save(qdUserWalletLog);
                }
            }
        });
        saveBatch(orderList);
        return updateBatchById(list);
    }

    @Override
    @Transactional
    public boolean confirmOrder(Long ascriptionStore) {
        QueryWrapper<QdPayOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",ascriptionStore);
        queryWrapper.eq("status","0");
        List<QdPayOrderInfo> list = qdPayOrderInfoService.list(queryWrapper);
        if (list.isEmpty()){
            throw new ServiceException("没有待确认订单或者未生成对账单");
        }
        list.forEach(m->{
            m.setStatus("1");
        });
        qdPayOrderInfoService.updateBatchById(list);
        //给所有订单的会员上级返佣金
        QdOrder order = new QdOrder();
        order.setStoreId(ascriptionStore);
        order.setBuyerStatus("1");
        order.setSellerStatus("1");
        List<QdOrder> list1 = this.list(order);
        if (list1.isEmpty()){
            return true;
        }
        list1.forEach(m->{
            m.setBuyerStatus("2");
            m.setSellerStatus("2");
//            //充值业绩
//            QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(m.getBuyerUserId()));
//            wallet.setListingFee(wallet.getListingFee().add(m.getListingFee()));
//            wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(m.getPrice()));//买入
//            wallet.setNowMoney(wallet.getNowMoney().add(m.getPrice()));
//            wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
//            userWalletService.updateById(wallet);
//            QdUserWallet wallet2 = userWalletService.getByUserId(String.valueOf(m.getSellerUserId()));
//            wallet2.setAchievement(wallet2.getAchievement().add(m.getPrice()));//卖出
//            userWalletService.updateById(wallet2);

            //然后增加佣金
//            QdUser user = qdUserService.getById(m.getBuyerUserId());
//            if (user.getSuperId()!=null){
//                QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(user.getSuperId()));
//                wallet1.setAllWallet(wallet1.getAllWallet().add(m.getPushAmount()));
//                wallet1.setWithdrawalWallet(wallet1.getWithdrawalWallet().add(m.getPushAmount()));
//                userWalletService.updateById(wallet1);
//                //插入日志
//                QdUserWalletLog qdUserWalletLog = new QdUserWalletLog();
//                qdUserWalletLog.setUserId(user.getSuperId());
//                qdUserWalletLog.setUserPhone(user.getSuperUserPhone());
//                qdUserWalletLog.setChangeAmount(m.getPushAmount());
//                qdUserWalletLog.setType("1");
//                qdUserWalletLog.setDetail(String.format("来自【%s】的佣金",m.getBuyerUserName()));
//                walletLogService.save(qdUserWalletLog);
//            }
        });
        String string = list1.stream().map(m -> String.valueOf(m.getBuyerUserId())).collect(Collectors.joining(","));
        if (StringUtils.isNotBlank(string)){
            QdUser user = new QdUser();
            user.setUserIds(string);
            List<QdUser> list2 = qdUserService.list(user);
            list2.forEach(m->m.setDealDay(m.getDealDay()+1));
            qdUserService.updateBatchById(list2);
        }
//        QdOrder order1 = new QdOrder();
//        order1.setStoreId(ascriptionStore);
//        order1.setSellerStatus("1");
//        List<QdOrder> list11 = this.list(order1);
//        list11.forEach(m->{
//            m.setSellerStatus("2");
//            QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(m.getSellerUserId()));
//            wallet.setAchievement(wallet.getAchievement().add(m.getNewPrice()));//卖出
//            userWalletService.updateById(wallet);
//        });
//        this.updateBatchById(list11);
        //更新订单为待上架
        return updateBatchById(list1);
    }

    @Override
    @Transactional
    public boolean mergeOrder(DataUpdateDTO dto) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+dto.getIds()+"')");
        List<QdOrder> list = this.list(queryWrapper);
        list.forEach(m->{
            m.setStatus("3");
        });
        Map<Long, List<QdOrder>> collect = list.stream().collect(Collectors.groupingBy(QdOrder::getSellerUserId));
        //循环求和
        List<QdOrder> list1 = new ArrayList<>();
        collect.forEach((k,v)->{
            BigDecimal sum = v.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sum1 = v.stream().map(QdOrder::getOldPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sum2 = v.stream().map(QdOrder::getListingFee).reduce(BigDecimal.ZERO, BigDecimal::add);
            QdOrder qdOrder = new QdOrder();
            qdOrder.setId(null);
            qdOrder.setSellerUserId(k);
            qdOrder.setPrice(sum);
            qdOrder.setOrderNo("HD"+ IdUtil.getSnowflakeNextId());
            qdOrder.setOldPrice(sum1);
            qdOrder.setListingFee(sum2);
            if("1".equals(dto.getStatus())){
                qdOrder.setStatus("1");
            }else {
                qdOrder.setStatus("1".equals(dto.getType())?"2":"0");
            }
            if (!"1".equals(dto.getNowStatus())){
                qdOrder.setDealTime(new Date());
            }
            qdOrder.setSellerUserPhone(v.get(0).getSellerUserPhone());
            qdOrder.setSellerUserName(v.get(0).getSellerUserName());
            qdOrder.setSellerUserPhone(v.get(0).getSellerUserPhone());
            qdOrder.setStoreId(v.get(0).getStoreId());
            qdOrder.setGoodId(v.get(0).getStoreId());
            qdOrder.setGoodImg(v.get(0).getGoodImg());
            qdOrder.setGoodName(v.get(0).getGoodName());
            list1.add(qdOrder);
        });
        updateBatchById(list);
        return saveBatch(list1);
    }

    @Override
    @Transactional
    public boolean transferOrder(DataUpdateDTO dto) {
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+dto.getIds()+"')");
        List<QdOrder> list = this.list(queryWrapper);
        List<QdChangeOrder> changeList = new ArrayList<>();
        QdUser user = qdUserService.getByUserPhone(dto.getUserPhone());
        list.forEach(m->{
            QdChangeOrder changeOrder = new QdChangeOrder();
            changeOrder.setOrderId(m.getId());
            changeOrder.setReceiveStatus("0");
            List<QdChangeOrder> list1 = changeOrderService.list(changeOrder);
            if (!list1.isEmpty()){
                throw new ServiceException("订单已申请转移");
            }
            if (!"0".equals(m.getSellerStatus())){
                throw new ServiceException("订单状态异常");
            }
            m.setStatus("5");
            QdStore store = storeService.getById(m.getStoreId());
            QdChangeOrder qdChangeOrder = new QdChangeOrder();
            qdChangeOrder.setOrderId(m.getId());
            qdChangeOrder.setType("2".equals(dto.getType())?"3":"2");
            qdChangeOrder.setOldStoreId(m.getStoreId());
            qdChangeOrder.setOldStoreName(store.getStoreName());
            qdChangeOrder.setOldStoreLeader(store.getStoreLeader());
            qdChangeOrder.setOldStoreLeaderId(store.getStoreLeaderId());
            qdChangeOrder.setOldStoreLeaderPhone(store.getStoreLeaderPhone());

            qdChangeOrder.setNewStoreName(user.getStoreName());
            qdChangeOrder.setNewStoreLeader(user.getStoreLeader());
            qdChangeOrder.setNewStoreLeaderId(user.getStoreLeaderId());
            qdChangeOrder.setNewStoreLeaderPhone(user.getStoreLeaderPhone());

            qdChangeOrder.setNewStoreId(user.getAscriptionStore());
            qdChangeOrder.setOldUserId(m.getSellerUserId());
            qdChangeOrder.setNewUserId(user.getId());
            qdChangeOrder.setOldUserPhone(m.getSellerUserPhone());
            qdChangeOrder.setNewUserPhone(user.getUserPhone());
            qdChangeOrder.setOldUserName(m.getSellerUserName());
            qdChangeOrder.setNewUserName(user.getNickName());
            qdChangeOrder.setOldPrice(m.getOldPrice());
            qdChangeOrder.setPrice(m.getPrice());
            changeList.add(qdChangeOrder);
        });
        //updateBatchById(list);
        return changeOrderService.saveBatch(changeList);
    }

    @Override
    @Transactional
    public boolean unpackOrder(DataUpdateDTO dto) {
        QdOrder order = getById(dto.getIds());
        if (order==null || !"0".equals(order.getSellerStatus())){
            throw new ServiceException("订单不存在");
        }
        if ("1".equals(order.getStatus())&&!"1".equals(dto.getStatus())){
            throw new ServiceException("无法将明日订单拆到今日");
        }
        BigDecimal money = new BigDecimal(dto.getMoney());
        if(money.compareTo(order.getPrice())>-1){
            throw new ServiceException("拆单金额必须小于原订单金额");
        }
        BigDecimal bili = order.getPrice().divide(order.getOldPrice(),6, RoundingMode.HALF_UP);
        BigDecimal oldPrice = money.divide(bili,2, RoundingMode.HALF_UP);
        BigDecimal fee = order.getListingFee().divide(bili,2, RoundingMode.HALF_UP);
        order.setPrice(order.getPrice().subtract(money));
        order.setOldPrice(order.getOldPrice().subtract(oldPrice));
        order.setListingFee(order.getListingFee().subtract(fee));
        QdOrder order1 = new QdOrder();
        BeanUtils.copyProperties(order,order1);
        if("1".equals(dto.getStatus())){
            order1.setStatus("1");
        }else {
            if ("1".equals(dto.getType())){
                order1.setStatus("2");
            }
        }
        order1.setId(null);
        order1.setCreateTime(new Date());
        order1.setOrderNo("CD"+ IdUtil.getSnowflakeNextId());
        order1.setPrice(money);
        order1.setOldPrice(oldPrice);
        order1.setListingFee(fee);
        updateById(order);
        return save(order1);
    }

    @Override
    public boolean saveInfo(QdOrder qdOrder) {
        QdUser user = qdUserService.getById(qdOrder.getSellerUserId());
        if (user==null){
            throw new ServiceException("用户不存在");
        }
        qdOrder.setSellerUserPhone(user.getUserPhone());
        qdOrder.setSellerUserName(user.getNickName());
        qdOrder.setOrderNo("OD" + IdUtil.getSnowflakeNextId());
        QdStore store = storeService.getById(user.getAscriptionStore());
        qdOrder.setStoreId(store.getId());
        qdOrder.setGoodId(store.getGroupOneGoodId());
        qdOrder.setGoodImg(store.getGroupOneImage());
        qdOrder.setGoodName(store.getGroupOneName());
        qdOrder.setDealTime(new Date());
        return save(qdOrder);
    }

    @Override
    @Transactional
    public boolean transferOrderUpdate(DataUpdateDTO dto) {
        QueryWrapper<QdChangeOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("FIND_IN_SET(id,'"+dto.getIds()+"')");
        List<QdChangeOrder> list = changeOrderService.list(queryWrapper);
        List<QdOrder> list1 = new ArrayList<>();
        list.forEach(m->{
            if (!"0".equals(m.getReceiveStatus())){
                throw new ServiceException("订单已处理，请刷新后重试！");
            }
            m.setReceiveStatus(dto.getStatus());
            if ("1".equals(dto.getStatus())){

                QdOrder order = getById(m.getOrderId());
                if (!"1".equals(order.getStatus())){
                    throw new ServiceException("原订单状态已发生改变，无法转移");
                }
                if (m.getPrice().compareTo(order.getPrice())!=0||m.getOldPrice().compareTo(order.getOldPrice())!=0){
                    throw new ServiceException("原订单金额已发生变化，无法转移！");
                }
                if ("3".equals(m.getType())){
                    QdUser qdUser = qdUserService.getById(m.getOldUserId());
                    if (qdUser==null){
                        throw new ServiceException("用户不存在");
                    }
                    //判断下级是否还有存单未完成
                    String string = qdUserService.queryAllChild(String.valueOf(m.getOldUserId()));
                    QueryWrapper<QdOrder> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.apply("FIND_IN_SET(seller_user_id,'"+string+"')");
                    queryWrapper1.ne("status","3");
                    queryWrapper1.and(q->q.eq("seller_status","1").or().apply("FIND_IN_SET(buyer_status,'1,2,3')"));
                    List<QdOrder> list2 = this.list(queryWrapper1);
                    if (!list2.isEmpty()){
                        throw new ServiceException("该团队用户中有未完成订单，请先完成订单后再转单");
                    }
                    QdUser qdUser1 = qdUserService.getById(m.getNewUserId());
                    if (qdUser1==null){
                        throw new ServiceException("转入用户不存在");
                    }
                    if (qdUser.getSuperId()!=null){
                        qdUserService.updatePushNum(String.valueOf(qdUser.getSuperId()),-1);
                        //减少原团队人数
                        List<QdUser> allParentMemberById = qdUserService.getAllParentMemberById(String.valueOf(qdUser.getSuperId()));
                        qdUserService.updateTeamNum(allParentMemberById.stream().map(m1->String.valueOf(m1.getId())).collect(Collectors.joining(",")),-qdUser.getTeamNum());
                    }
                    if (!Objects.equals(qdUser1.getId(), qdUser1.getStoreLeaderId())){
                        //增加新团队人数
                        List<QdUser> allParentMemberById = qdUserService.getAllParentMemberById(String.valueOf(qdUser1.getId()));
                        qdUserService.updateTeamNum(allParentMemberById.stream().map(m1->String.valueOf(m1.getId())).collect(Collectors.joining(",")),qdUser.getTeamNum());
                        qdUserService.updatePushNum(String.valueOf(qdUser1.getId()),1);
                        qdUser.setSuperId(m.getNewUserId());
                        qdUser.setSuperUserName(m.getNewUserName());
                        qdUser.setSuperUserPhone(m.getNewUserPhone());
                        qdUser.setAscriptionStore(m.getNewStoreId());
                        qdUser.setStoreName(m.getNewStoreName());
                        qdUser.setStoreLeader(m.getNewStoreLeader());
                        qdUser.setStoreLeaderId(m.getNewStoreLeaderId());
                        qdUser.setStoreLeaderPhone(m.getNewStoreLeaderPhone());
                        qdUser.setStoreLeaderImg(qdUser1.getStoreLeaderImg());
                        qdUserService.updateById(qdUser);
                    }
                    //更新团队归属店铺
                    QueryWrapper<QdUser> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.apply("FIND_IN_SET(id,'"+string+"')");
                    List<QdUser> list4 = qdUserService.list(queryWrapper3);
                    list4.forEach(n->{
                        n.setAscriptionStore(m.getNewStoreId());
                        n.setStoreName(m.getNewStoreName());
                        n.setStoreLeader(m.getNewStoreLeader());
                        n.setStoreLeaderId(m.getNewStoreLeaderId());
                        n.setStoreLeaderPhone(m.getNewStoreLeaderPhone());
                        n.setStoreLeaderImg(qdUser1.getStoreLeaderImg());
                    });
                    qdUserService.updateBatchById(list4);
                    //更新订单归属店铺
                    QueryWrapper<QdOrder> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.apply("FIND_IN_SET(seller_user_id,'"+string+"')");
                    queryWrapper2.and(q->q.eq("seller_status","0"));
                    List<QdOrder> list3 = this.list(queryWrapper2);
                    list3.forEach(n->{
                        n.setStoreId(m.getNewStoreId());
                    });
                    updateBatchById(list3);
                }else {
                    QdOrder qdOrder = this.getById(m.getOrderId());
                    QdStore store = storeService.getById(m.getNewStoreId());
                    qdOrder.setSellerUserId(m.getNewUserId());
                    qdOrder.setSellerUserPhone(m.getNewUserPhone());
                    qdOrder.setSellerUserName(m.getNewUserName());
                    qdOrder.setGoodId(store.getGroupOneGoodId());
                    qdOrder.setGoodImg(store.getGroupOneImage());
                    qdOrder.setGoodName(store.getGroupOneName());
                    qdOrder.setStoreId(m.getNewStoreId());
                    list1.add(qdOrder);
                }
            }
        });
        if (!list1.isEmpty()){
            updateBatchById(list1);
        }
        return changeOrderService.updateBatchById(list);
    }

    @Override
    @Transactional
    public void autoBuyOrder() {
        QdUser user = new QdUser();
        user.setAutoStatus("1");
        List<QdUser> list = qdUserService.list(user);
        list.forEach(m->{
            QdOrder order = new QdOrder();
            order.setSellerUserId(m.getId());
            order.setSellerStatus("0");
            order.setStatus("0");
            order.setStoreId(m.getAscriptionStore());
            List<QdOrder> list1 = this.list(order);
            //查询店铺缓存
            QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + m.getAscriptionStore());
            if (cacheMap==null){
                cacheMap = storeService.getIndexInfo(m.getAscriptionStore());
                redisCache.setCacheObject(CacheConstants.STORE_INFO + m.getAscriptionStore(), cacheMap);
            }

            BigDecimal bili = m.getGiftValue();
            if (bili==null){
                bili = cacheMap.getAppreciation();
            }
            QdStoreVo finalCacheMap = cacheMap;
            BigDecimal finalBili = bili;
            list1.forEach(n->{
                n.setBuyerStatus("0");
                n.setDealTime(new Date());
                n.setBuyerUserId(m.getId());
                n.setBuyerUserName(m.getNickName());
                n.setBuyerUserPhone(m.getUserPhone());
                n.setBuyerBalance("0");
                n.setBuyerType("3");
                n.setSellerStatus("1");
                n.setListingFee(n.getPrice().multiply(finalCacheMap.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                n.setNewPrice(n.getPrice().multiply(finalBili.add(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                n.setPushAmount(n.getPrice().multiply(finalCacheMap.getPushFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                this.updateById(n);

                //20241213 购买后计算业绩
                //累计购买上架费
                QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(user.getId()));
                wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(n.getPrice()));
                wallet.setNowMoney(wallet.getNowMoney().add(n.getPrice()));
                wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
                wallet.setListingFee(wallet.getListingFee().add(n.getListingFee()));
                userWalletService.updateById(wallet);
                //更新业绩
                QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(n.getSellerUserId()));
                wallet1.setAchievement(wallet1.getAchievement().add(n.getPrice()));
                userWalletService.updateById(wallet1);

                QdUser sellerUser = qdUserService.getById(n.getSellerUserId());
                //插入对账信息
                QdPay qdPay = new QdPay();
                qdPay.setBuyerBankInfo(user.getBankInfo());
                qdPay.setBuyerBankNo(user.getBankNo());
                qdPay.setBuyerBankName(user.getBankName());
                qdPay.setBuyerUserId(user.getId());
                qdPay.setBuyerUserName(user.getNickName());
                qdPay.setBuyerUserPhone(user.getUserPhone());
                qdPay.setBuyerBalance("0");
                qdPay.setAmount(n.getPrice().subtract(n.getListingFee()).subtract(n.getPushAmount()));
                qdPay.setSellerUserId(n.getSellerUserId());
                qdPay.setSellerUserName(n.getSellerUserName());
                qdPay.setSellerUserPhone(n.getSellerUserPhone());
                qdPay.setSellerBalance("0");
                qdPay.setStatus("0");
                qdPay.setOrderNo(n.getOrderNo());
                qdPay.setSellerBankInfo(sellerUser.getBankInfo());
                qdPay.setSellerBankNo(sellerUser.getBankNo());
                qdPay.setSellerBankName(sellerUser.getBankName());
                qdPayService.save(qdPay);
            });
        });
    }

    @Override
    public void autoAmountOrder() {
        QdUser user = new QdUser();
        user.setAllAmountStatus("1");
        List<QdUser> list = qdUserService.list(user);
        list.forEach(m->{
            //查询店铺缓存
            QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + m.getAscriptionStore());
            if (cacheMap==null){
                cacheMap = storeService.getIndexInfo(m.getAscriptionStore());
                redisCache.setCacheObject(CacheConstants.STORE_INFO + m.getAscriptionStore(), cacheMap);
            }

            BigDecimal bili = m.getGiftValue();
            if (bili==null){
                bili = cacheMap.getAppreciation();
            }
            QdOrder qdOrder = new QdOrder();
            qdOrder.setSellerUserId(m.getId());
            qdOrder.setSellerStatus("0");
            qdOrder.setStatus("0");
            List<QdOrder> list1 = list(qdOrder);
            BigDecimal buyAmount = list1.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (buyAmount.compareTo(BigDecimal.ZERO)>0){
               QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
               queryWrapper.le("price",buyAmount);
               queryWrapper.eq("seller_status","0");
               queryWrapper.eq("status","0");
               queryWrapper.eq("store_id",m.getAscriptionStore());
               queryWrapper.last("order by price desc limit 1");
               QdOrder order = this.getOne(queryWrapper);
               if (order!=null){
                   order.setBuyerStatus("0");
                   order.setDealTime(new Date());
                   order.setBuyerUserId(m.getId());
                   order.setBuyerUserName(m.getNickName());
                   order.setBuyerUserPhone(m.getUserPhone());
                   order.setBuyerBalance("0");
                   order.setBuyerType("3");
                   order.setSellerStatus("1");
                   order.setListingFee(order.getPrice().multiply(cacheMap.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                   order.setNewPrice(order.getPrice().multiply(bili.add(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                   order.setPushAmount(order.getPrice().multiply(cacheMap.getPushFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
                   this.updateById(order);

                   //20241213 购买后计算业绩
                   //累计购买上架费
                   QdUserWallet wallet = userWalletService.getByUserId(String.valueOf(user.getId()));
                   wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(order.getPrice()));
                   wallet.setNowMoney(wallet.getNowMoney().add(order.getPrice()));
                   wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
                   wallet.setListingFee(wallet.getListingFee().add(order.getListingFee()));
                   userWalletService.updateById(wallet);
                   //更新业绩
                   QdUserWallet wallet1 = userWalletService.getByUserId(String.valueOf(order.getSellerUserId()));
                   wallet1.setAchievement(wallet1.getAchievement().add(order.getPrice()));
                   userWalletService.updateById(wallet1);

                   QdUser sellerUser = qdUserService.getById(order.getSellerUserId());
                   //插入对账信息
                   QdPay qdPay = new QdPay();
                   qdPay.setBuyerBankInfo(user.getBankInfo());
                   qdPay.setBuyerBankNo(user.getBankNo());
                   qdPay.setBuyerBankName(user.getBankName());
                   qdPay.setBuyerUserId(user.getId());
                   qdPay.setBuyerUserName(user.getNickName());
                   qdPay.setBuyerUserPhone(user.getUserPhone());
                   qdPay.setBuyerBalance("0");
                   qdPay.setAmount(order.getPrice().subtract(order.getListingFee()).subtract(order.getPushAmount()));
                   qdPay.setSellerUserId(order.getSellerUserId());
                   qdPay.setSellerUserName(order.getSellerUserName());
                   qdPay.setSellerUserPhone(order.getSellerUserPhone());
                   qdPay.setSellerBalance("0");
                   qdPay.setStatus("0");
                   qdPay.setOrderNo(order.getOrderNo());
                   qdPay.setSellerBankInfo(sellerUser.getBankInfo());
                   qdPay.setSellerBankNo(sellerUser.getBankNo());
                   qdPay.setSellerBankName(sellerUser.getBankName());
                   qdPayService.save(qdPay);
               }
           }
        });
    }

    @Override
    @Transactional
    public boolean updateListingStatus(QdOrder info) {
        QdStore store = storeService.getById(info.getStoreId());
        if (store.getGroupingFee().compareTo(BigDecimal.ZERO)>0){
            listingPoints(store, info);
        }
        return updateById(info);
    }
}
